<template>
  <div class="app-container">
    <div 
      class="filter-container" 
      style="margin-bottom: 20px;">
      <div class="top-search">
        <el-input
          v-model="listQuery.symbol"
          placeholder="查询交易对"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button
          v-waves
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >{{ $t('table.search') }}</el-button>
        <div class="filter-item">
          |自动刷新
          <el-select
            v-model="freshRate"
            style="width: 90px"
            @change="setFreshRate"
          >
            <el-option 
              v-for="item in freshRateList" 
              :key="item.label" 
              :label="item.label" 
              :value="item.value" />
          </el-select>
          <el-switch
            v-model="listQuery.isRefresh"
            active-color="#13ce66"
            inactive-color="#dcdfe6"
            @change="toggleFresh" />
        </div>
        <el-select
          v-model="listQuery.percent"
          style="width: 90px"
          class="filter-item"
        >
          <el-option 
            v-for="item in percentOptions" 
            :key="item.label" 
            :label="item.label" 
            :value="item.value" />
        </el-select>
        <!-- <el-input
                v-model="listQuery.total"
                placeholder="总价大于(w)"
                style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="handleFilter"
            /> -->
      </div>
      <div style="display: flex;">
        <div style="margin-right: 20px;">过滤</div>
        <el-checkbox-group 
          v-model="checkList" 
          @change="handleCheckedCoin">
          <el-checkbox 
            v-for="(item, index) in coinList" 
            :key="index" 
            :label="item.englishName">{{ item.remark }}</el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="filter-list">
        <el-collapse 
          v-model="activeNames" 
          accordion>
          <el-collapse-item 
            title="收起" 
            name="1" 
            class="filter-list-item">
            <template 
              slot="title" 
              style="color: #409EFF">
              {{ collapseWord }}<i 
                :class="activeNames ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" 
                class="header-icon"/>
            </template>
            <div class="list">
              过滤ID <el-tag
                v-for="(tag, index) in tableFilterList"
                :key="index"
                :disable-transitions="false"
                closable
                @close="handleClose(tag)">
                {{ tag.symbol }}
              </el-tag>
            </div>
            <div 
              v-for="(item, index) in tableFilterList" 
              :key="index"/>
          </el-collapse-item>
        </el-collapse>
      </div>
      <div class="filter-container">
        <el-checkbox-group 
          v-model="showColumnList" 
          @change="handleColumn">
          <el-checkbox 
            v-for="column in filterColumn" 
            :key="column.value" 
            :label="column.value">{{ column.label }}</el-checkbox>
        </el-checkbox-group>
      </div>
    </div>

    <el-table 
      v-loading="listLoading" 
      :key="tableKey" 
      :data="tableList" 
      border 
      fit 
      highlight-current-row 
      style="width: 100%;" 
      @sort-change="sortChange" >
      <el-table-column 
        label="交易对" 
        prop="symbol" 
        align="center" 
        min-width="120">
        <template slot-scope="scope">
          <span style="color: #9ee5ed">{{ scope.row.symbol }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        label="价格差" 
        prop="subPrice" 
        sortable 
        align="center" 
        min-width="120">
        <template slot-scope="scope">
          <span style="color: #ff8f84">{{ floatMul(scope.row.subPriceRate, 100) + '%' }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        label="买入平台" 
        prop="maxPriceExchange" 
        align="center" 
        min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.maxPriceExchange }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        label="卖出平台" 
        prop="minPriceExchange" 
        align="center" 
        min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.minPriceExchange }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        label="买入价格" 
        prop="maxPrice" 
        sortable 
        align="center" 
        min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.maxPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        label="卖出价格" 
        prop="minPrice" 
        sortable 
        align="center" 
        min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.minPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        v-if="showColumn['bidSize']" 
        label="买入数量" 
        prop="bidSize" 
        sortable 
        align="center" 
        min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.bidSize }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        v-if="showColumn['askSize']" 
        label="卖出数量" 
        prop="askSize" 
        sortable 
        align="center" 
        min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.askSize }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        v-if="showColumn['buyTotalPrice']" 
        label="买入总价¥" 
        prop="buyTotalPrice" 
        sortable 
        align="center" 
        min-width="120">
        <template slot-scope="scope">
          <span :style="{color: getTextColor(scope.row.buyTotalPrice)}">{{ floorNum(scope.row.buyTotalPrice) }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        v-if="showColumn['sellTotalPrice']" 
        label="卖出总价¥" 
        prop="sellTotalPrice" 
        sortable 
        align="center" 
        min-width="120">
        <template slot-scope="scope">
          <span :style="{color: getTextColor(scope.row.sellTotalPrice)}">{{ floorNum(scope.row.sellTotalPrice) }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        v-if="showColumn['updateTime']" 
        label="更新时间" 
        prop="updateTime" 
        sortable 
        align="center" 
        min-width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        v-if="showColumn['id']" 
        label="ID" 
        prop="id" 
        align="center" 
        min-width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        label="操作" 
        align="center">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            @click="handleFilterData(scope.row)">过滤</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
    fetchList,
    getSearchInfo,
    fetchPv,
    createArticle,
    updateArticle
} from "@/api/article";
import waves from "@/directive/waves"; // Waves directive
import { parseTime, floatMul, getPriceNum } from "@/utils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

const calendarTypeOptions = [
    { key: "CN", display_name: "China" },
    { key: "US", display_name: "USA" },
    { key: "JP", display_name: "Japan" },
    { key: "EU", display_name: "Eurozone" }
];

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name;
    return acc;
}, {});

export default {
    name: "ComplexTable",
    components: { Pagination },
    directives: { waves },
    filters: {
        statusFilter(status) {
            const statusMap = {
                published: "success",
                draft: "info",
                deleted: "danger"
            };
            return statusMap[status];
        },
        typeFilter(type) {
            return calendarTypeKeyValue[type];
        }
    },
    data() {
        return {
            freshRate: '5000',
            freshRateList: [
                {label: '5S', value: '5000'},
                {label: '10S', value: '10000'},
                {label: '30S', value: '30000'},
                {label: '60S', value: '60000'}
            ],
            activeNames: null,
            tableFilterList: [],
            filterColumn: [
                {label: '买入数量', value: 'bidSize'},
                {label: '卖出数量', value: 'askSize'},
                {label: '买入总价', value: 'buyTotalPrice'},
                {label: '卖出总价', value: 'sellTotalPrice'},
                {label: '更新时间', value: 'updateTime'},
                {label: 'ID', value: 'id'}
            ],
            showColumnList: ['bidSize', 'askSize', 'buyTotalPrice', 'sellTotalPrice', 'updateTime', 'id'],
            tableKey: 0,
            list: [],
            total: 0,
            listLoading: true,
            listQuery: {
                isRefresh: false,
                percent: 1,
                total: '',
                importance: undefined,
                symbol: '',
                exchangeName: '',
                sort: "+id"
            },
            checkList: [],
            coinList: [
                {remark: '火币', englishName: 'huobi'},
                {remark: '币安', englishName: 'bian'},
                {remark: 'Okex', englishName: 'okex'},
                {remark: 'Gate', englishName: 'gate'},
                {remark: 'Mexc', englishName: 'mexc'},
                {remark: 'Aex', englishName: 'aex'},
                {remark: 'Poloniex', englishName: 'poloniex'},
                {remark: 'Kucoin', englishName: 'kucoin'}
            ],
            percentOptions: [
                {label: '0%', value: 0},
                {label: '1%', value: 1},
                {label: '10%', value: 10},
                {label: '100%', value: 100}
            ],
            importanceOptions: [1, 2, 3],
            calendarTypeOptions,
            sortOptions: [
                { label: "ID Ascending", key: "+id" },
                { label: "ID Descending", key: "-id" }
            ],
            temp: {
                id: undefined,
                importance: 1,
                remark: "",
                timestamp: new Date(),
                title: "",
                type: "",
                status: "published"
            },
            textMap: {
                update: "Edit",
                create: "Create"
            },
            timeout: null
        };
    },
    computed: {
        collapseWord() {
            return this.activeNames ? '收起' : '展开';
        },
        showColumn() {
            let list = this.showColumnList;
            return {
                bidSize: list.includes('bidSize'),
                askSize: list.includes('askSize'),
                buyTotalPrice: list.includes('buyTotalPrice'),
                sellTotalPrice: list.includes('sellTotalPrice'),
                updateTime: list.includes('updateTime'),
                id: list.includes('id')
            };
        },
        tableList() {
            let tableFilterList = this.tableFilterList.map(item => item.symbol);
            return this.list.filter(item => {
                return !tableFilterList.includes(item.symbol);
            }).filter(item => this.floatMul(item.subPriceRate, 100) > this.listQuery.percent);
        }
    },
    created() {
        this.useCache();
        this.getSearchVo();
        this.getList();
    },
    destroyed() {
        this.clearFreshTime();
    },
    methods: {
        floatMul,
        floorNum(num) {
            return num ? Math.floor(num) : num;
        },
        getTextColor(num) {
            const colors = ['#000', '#87ceeb', '#ff0000'];
            return colors[getPriceNum(num)];
        },
        useCache() {
            const store = localStorage.getItem('tableFilter');
            const data = store ? JSON.parse(store) : [];
            this.tableFilterList = data;
        },
        changeFresh(time) {
            this.clearFreshTime();
            this.timeout = setInterval(() => {
                this.getList();
            }, time || 5000);
        },
        clearFreshTime() {
            this.timeout && clearInterval(this.timeout);
            this.timeout = null;
        },
        toggleFresh(val) {
            if (val) {
                this.changeFresh(this.freshRate);
            } else {
                this.clearFreshTime();
            }
        },
        setFreshRate() {
            if (this.listQuery.isRefresh) {
                this.changeFresh(this.freshRate);
            }
        },
        getSearchVo() {
            getSearchInfo().then(res => {
                let list = res.content ? res.content.list : [];
                this.coinList = list;
            });
        },
        handleClose(tag) {
            let index = this.tableFilterList.findIndex(item => item.id === tag.id);
            this.tableFilterList.splice(index, 1);
        },
        handleColumn(val) {
            this.showColumnList = val;
        },
        handleFilterData(data) {
            let list = this.tableFilterList;
            let a = list.map(item => item.id).indexOf(data.id) > -1;
            if (!a) {
                list.push(data);
            }
            localStorage.setItem('tableFilter', JSON.stringify(list));
            this.$set(this, 'tableFilterList', list);
        },
        handleCheckedCoin(val) {
            // console.log(this.checkList, val);
            this.getList();
        },
        getList() {
            this.listLoading = true;
            let {symbol} = this.listQuery;
            let exchangeName = this.checkList ? this.checkList.join(',') : null;
            let params = {};
            exchangeName && (params.exchangeName = exchangeName);
            symbol && (params.symbol = symbol);
            fetchList(params).then(res => {
                let list = res.content || [];
                this.list = list.map(item => {
                    return {
                        ...item,
                        id: item.symbol + item.maxPriceExchange + item.minPriceExchange
                    };
                });
                this.listLoading = false;
            });
        },
        handleFilter() {
            this.listQuery.page = 1;
            this.getList();
        },
        sortChange(data) {
            const { prop, order } = data;
            if (prop === "id") {
                this.sortByID(order);
            }
        },
        sortByID(order) {
            if (order === "ascending") {
                this.listQuery.sort = "+id";
            } else {
                this.listQuery.sort = "-id";
            }
            this.handleFilter();
        }
    },
};
</script>
<style lang="scss" scoped>
    // .filter-list-item
    .top-search {
        display: flex;
        align-items: center;
    }
    .filter-list .el-collapse {
        border: none;
    }
    .el-tag + .el-tag {
        margin-left: 10px;
        margin-bottom: 10px;
    }
</style>
<style>
    .filter-list .el-collapse-item__arrow {
        display: none;
    }
</style>